package com.xidian.zhiancloud.service.equipFacility;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xidian.zhiancloud.dao.*;
import com.xidian.zhiancloud.dao.syset.PositionMapper;
import com.xidian.zhiancloud.dao.syset.SysUserMapper;
import com.xidian.zhiancloud.dao.syset.usermanage.OrganizationMapper;
import com.xidian.zhiancloud.enums.GeneralResponseEnums;
import com.xidian.zhiancloud.exception.CustomizeException;
import com.xidian.zhiancloud.model.*;
import com.xidian.zhiancloud.model.syset.Organization;
import com.xidian.zhiancloud.model.syset.PositionList;
import com.xidian.zhiancloud.model.syset.SysUser;
import com.xidian.zhiancloud.qo.equipFacility.OhPlanDraftQO;
import com.xidian.zhiancloud.qo.equipFacility.OhPlanExecuteQO;
import com.xidian.zhiancloud.qo.equipFacility.OhPlanRegisterQO;
import com.xidian.zhiancloud.vo.equipFacility.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @ClassName OhPlanExecuteService
 * @Description 检修计划执行
 * @Author Halo
 **/
@Service
public class OhPlanExecuteService {

    @Autowired
    private OhPlanDraftMapper ohPlanDraftMapper;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private OhObjectMapper ohObjectMapper;

    @Autowired
    private OhPlanExcuteMapper ohPlanExcuteMapper;

    @Autowired
    private EqFacMngMapper eqFacMngMapper;

    @Autowired
    private OhRegisterService ohRegisterService;

    @Autowired
    private OhRegisterMapper ohRegisterMapper;

    @Autowired
    private OhPlanRegisterMapper ohPlanRegisterMapper;

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private DeviceTypeMapper deviceTypeMapper;

    @Autowired
    private OhStandardMapper ohStandardMapper;


    /**
     * 列表查询
     * @param ohPlanDraftQO
     * @return
     */
    public IPage<OhPlanDraftVO> getListByQO(OhPlanDraftQO ohPlanDraftQO) {
        Page<OhPlanDraftVO> page = new Page<>(ohPlanDraftQO.getCurrent(), ohPlanDraftQO.getSize());
        OrderItem orderItem = new OrderItem();
        orderItem.setColumn("create_time").setAsc(false);
        page.getOrders().add(orderItem);
        IPage<OhPlanDraftVO> list = ohPlanDraftMapper.selectByQO(page, ohPlanDraftQO);

        List<OhPlanDraftVO> new_list = new ArrayList<>();

        //过滤
        for (OhPlanDraftVO record : list.getRecords()) {

            if(record.getState() == 0){
                continue;
            }

            Organization org = organizationMapper.selectById(record.getOrgId());
            record.setOrganizationName(org == null ? "该部门不存在" : org.getName());
            SysUser creator = sysUserMapper.selectById(record.getCreator());
            record.setCreateName(creator == null ? "该用户不存在" : creator.getName());

            //检修人包含当前用户
            LambdaQueryWrapper<OhObject> queryWrapper = Wrappers.lambdaQuery();
            queryWrapper.eq(OhObject::getOhPlanDraftId,record.getId());
            List<OhObject> ohObjects = ohObjectMapper.selectList(queryWrapper);

            for (OhObject object : ohObjects) {
                long[] array = Arrays.stream(object.getOherId().split(",")).mapToLong(Long::parseLong).toArray();
                int i = 0;
                for (; i < array.length; i++) {
                    if(array[i] == ohPlanDraftQO.getUserId()){
                        new_list.add(record);
                        break;
                    }
                }

                if(i < array.length){
                    break;
                }
            }

        }

        list.setRecords(new_list);
        System.out.println("最新列表长度：" + new_list.size());

        return list;
    }

    /**
     * 检修计划执行--提交
     * @param id 检修计划id
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean submit(Long id,Long currentUserId){

        OhPlanExecute execute = new OhPlanExecute();

        execute.setExecutor(currentUserId);
        execute.setOhPlanDraftId(id);

        //添加到检修计划执行表
        int insert = ohPlanExcuteMapper.insert(execute);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.SUBMIT_FAILED);
        }

        //判断检修计划是否执行完毕  通过判断检修计划登记的条数与需要检修的设备的检修项数之和是否相等
        //查询当前检修计划的所有检修对象
        LambdaQueryWrapper<OhObject> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OhObject::getOhPlanDraftId,id);
        List<OhObject> ohObjects = ohObjectMapper.selectList(queryWrapper);

        int count = 0;
        for (OhObject obj : ohObjects) {
            //查询当前检修设备的检修项数
            LambdaQueryWrapper<OhStandard> queryStandard = new LambdaQueryWrapper<>();
            queryStandard.eq(OhStandard::getEqFacId,obj.getEqFacId());
            List<OhStandard> list = ohStandardMapper.selectList(queryStandard);
            //所有检修设备的检修项之和
            count += list.size();
        }

        //查询当前检修计划在检修计划登记表中的条数
        LambdaQueryWrapper<OhPlanRegister> queryRegister = new LambdaQueryWrapper<>();
        queryRegister.eq(OhPlanRegister::getPlanId,id);
        List<OhPlanRegister> registerList = ohPlanRegisterMapper.selectList(queryRegister);

        //判断是所以项数和计划登记条数是否相等
        if(count != registerList.size()){

            throw new CustomizeException((GeneralResponseEnums.INCOMPLETE_EXECUTION));
        }

        //修改检修计划状态
        OhPlanDraft planDraft = ohPlanDraftMapper.selectById(id);
        planDraft.setState(2);
        int ret = ohPlanDraftMapper.updateById(planDraft);
        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        return true;
    }

    /**
     * 检修之前
     * 检修计划执行--查看
     * @param ohPlanExecuteQO
     * @return
     */
    public IPage<OhPlanExcuteVO> getListById(OhPlanExecuteQO ohPlanExecuteQO,Long userId){

        Page<OhPlanExcuteVO> page = new Page<>(ohPlanExecuteQO.getCurrent(), ohPlanExecuteQO.getSize());
        IPage<OhPlanExcuteVO> list = ohObjectMapper.selectEqFacByQO(page,ohPlanExecuteQO);

        list.getRecords().forEach(vo -> {

            //查询管辖部门名称
            Organization organization = organizationMapper.selectById(vo.getMngCtrDeptId());
            vo.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

            //当前用户名称  就是检修人
            SysUser sysUser = sysUserMapper.selectById(userId);
            vo.setExecutorName(sysUser == null ? "该用户不存在" : sysUser.getName());

            PositionList position = positionMapper.selectById(vo.getPosition());
            vo.setPositionName(position == null ? "该区域不存在" : position.getName());
        });

        return list;
    }

    /**
     * 查看设备和检修信息
     * @param eqFacMngId 设备设施id
     * @return
     */
    public OhPlanEqFacMngVO getEqFacMngMsgById(Long eqFacMngId,Long planId){

        OhPlanEqFacMngVO vo = new OhPlanEqFacMngVO();

        //查询设备信息
        EqFacMng eqFacMng = eqFacMngMapper.selectById(eqFacMngId);
        if(eqFacMng == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        BeanUtils.copyProperties(eqFacMng,vo);

        Organization organization = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setDepartmentName(organization == null ? "该部门不存在" : organization.getName());

        PositionList position = positionMapper.selectById(eqFacMng.getPosition());
        vo.setPositionName(position == null ? "该区域位置不存在" : position.getName());

        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceTypeName(deviceType == null ? "该类型不存在" : deviceType.getName());

        //查询检修项
        LambdaQueryWrapper<OhStandard> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OhStandard::getEqFacId,eqFacMngId);
        List<OhStandard> ohStandards = ohStandardMapper.selectList(queryWrapper);

        List<OhStandardStatusVO> list = new ArrayList<>();

        //判断是否检修
        for (OhStandard obj : ohStandards) {
            OhStandardStatusVO standardStatusVO = new OhStandardStatusVO();
            BeanUtils.copyProperties(obj,standardStatusVO);

            LambdaQueryWrapper<OhPlanRegister> query = new LambdaQueryWrapper<>();
            query.eq(OhPlanRegister::getEqFacId,eqFacMngId);
            query.eq(OhPlanRegister::getPlanId,planId);
            query.eq(OhPlanRegister::getOhStandardId,obj.getId());
            List<OhPlanRegister> ohPlanRegisters = ohPlanRegisterMapper.selectList(query);

            if(ohPlanRegisters == null || ohPlanRegisters.size() == 0){
                standardStatusVO.setIsRepaired(0);
            }else{
                standardStatusVO.setIsRepaired(1);
            }
            list.add(standardStatusVO);
        }

        vo.setStandardList(list);

        return vo;
    }

    /**
     * 检修计划执行 -- 执行 -- 检修(检修登记）
     * @param executorId 执行人id
     * @param ohPlanRegisterQO 检修登记信息
     * @return
     */
    @Transactional(rollbackFor = {RuntimeException.class, Error.class, CustomizeException.class})
    public Boolean repair(Long executorId, OhPlanRegisterQO ohPlanRegisterQO){

        OhStandard ohStandard = ohStandardMapper.selectById(ohPlanRegisterQO.getOhStandardId());
        if(ohStandard == null){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        OhRegister register = new OhRegister();

        BeanUtils.copyProperties(ohPlanRegisterQO,register);

        //执行  添加到检修登记
        register.setEqFacId(ohPlanRegisterQO.getEqFacId());
        register.setRepairUsersId(executorId+",");
        register.setCreator(executorId);
        register.setCreateTime(new Date());
        register.setIsSubmitted(1);
        register.setOhCont(ohStandard.getOhCont());
        register.setOhTypeId(ohStandard.getOhTypeId());
        register.setProtectStep(ohStandard.getProtectStep());
        register.setOhTime(new Date());

        Boolean result = ohRegisterService.add(register);

        if(result == false){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        //保存检修登记id
        OhPlanRegister ohPlanRegister = new OhPlanRegister();
        ohPlanRegister.setEqFacId(ohPlanRegisterQO.getEqFacId());
        ohPlanRegister.setPlanId(ohPlanRegisterQO.getPlanId());
        ohPlanRegister.setRegisterId(register.getId());
        ohPlanRegister.setOhStandardId(ohPlanRegisterQO.getOhStandardId());

        int insert = ohPlanRegisterMapper.insert(ohPlanRegister);
        if(insert == 0){
            throw new CustomizeException(GeneralResponseEnums.OPERATE_DAILED);
        }

        return true;
    }

    /**
     * 检修项检修之后-【编辑】可修改
     * @param ohRegister 修改后的检修登记信息
     * @return
     */
    public Boolean updateById(OhRegister ohRegister){

        if (ohRegister == null){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }

        int ret = ohRegisterMapper.updateById(ohRegister);

        if(ret == 0){
            throw new CustomizeException(GeneralResponseEnums.UPDATE_FAILED);
        }
        return true;
    }

    /**
     * 检修之后
     * 检修计划制定 -- 执行 -- 查看
     * @param ohPlanRegisterQO
     * @return
     */
    public EqFacAndRegisterVO lookOver(OhPlanRegisterQO ohPlanRegisterQO){

        EqFacAndRegisterVO vo = new EqFacAndRegisterVO();

        /*//根据检修计划id和设备设施id查找对应的检修登记id
        LambdaQueryWrapper<OhPlanRegister> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(OhPlanRegister::getEqFacId,ohPlanRegisterQO.getEqFacId());
        queryWrapper.eq(OhPlanRegister::getPlanId,ohPlanRegisterQO.getPlanId());
        List<OhPlanRegister> list = ohPlanRegisterMapper.selectList(queryWrapper);

        if(list.size() == 0){
            return vo;
        }

        //查找检修登记
        OhRegister ohRegister = ohRegisterMapper.selectById(list.get(0).getRegisterId());
        if(ohRegister == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        vo.setOhRegister(ohRegister);*/

        //查找设备设施基本信息
        EqFacMng eqFacMng = eqFacMngMapper.selectById(ohPlanRegisterQO.getEqFacId());
        if(eqFacMng == null){
            throw new CustomizeException(GeneralResponseEnums.UPLOAD_FAILED);
        }
        String mngment = eqFacMng.getMngment();
        String name = "";
        long[] array = Arrays.stream(mngment.split(",")).mapToLong(Long::parseLong).toArray();
        for (long id : array) {
            SysUser sysUser = sysUserMapper.selectById(id);
            if(sysUser != null){
                name += sysUser.getName() + ",";
            }
        }
        eqFacMng.setMngment(name);
        vo.setEqFacMng(eqFacMng);

        Organization organization = organizationMapper.selectById(eqFacMng.getMngCtrDeptId());
        vo.setMngCtrDeptName(organization == null ? "该部门不存在" : organization.getName());

        PositionList positionList = positionMapper.selectById(eqFacMng.getPosition());
        vo.setPositionName(positionList == null ? "该区域不存在" : positionList.getName());

        DeviceType deviceType = deviceTypeMapper.selectById(eqFacMng.getDeviceTypeId());
        vo.setDeviceTypeName(deviceType == null ? "该设备设施不存在" : deviceType.getName());

        //查询检修项信息
        OhStandard ohStandard = ohStandardMapper.selectById(ohPlanRegisterQO.getOhStandardId());
        vo.setOhStandard(ohStandard);

        return vo;
    }

    /**
     * 检修之后，查看单独检修项检修信息
     * @param ohPlanRegisterQO
     * @return
     */
    public OhRegister getRegister(OhPlanRegisterQO ohPlanRegisterQO){

        //查询检修登记id
        LambdaQueryWrapper<OhPlanRegister> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OhPlanRegister::getEqFacId,ohPlanRegisterQO.getEqFacId());
        queryWrapper.eq(OhPlanRegister::getOhStandardId,ohPlanRegisterQO.getOhStandardId());
        queryWrapper.eq(OhPlanRegister::getPlanId,ohPlanRegisterQO.getPlanId());
        List<OhPlanRegister> list = ohPlanRegisterMapper.selectList(queryWrapper);

        OhPlanRegister ohPlanRegister = list.get(0);

        //查询检修登记
        OhRegister ohRegister = ohRegisterMapper.selectById(ohPlanRegister.getRegisterId());

        return ohRegister;
    }
}
